package com.GPS;



import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;


import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
//import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
//import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
//import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;


//TODO: ��������� ����������� �� ��� ���� 

//TODO: ������ ������������ ���������

//TODO: ���� �������� GPS, �� ������ ���������� �������� � ���� - �������� ������������ � �� ���������

//TODO: ������ ������ � �������� �������

//TODO: ��������� ������ ��� ����������� �� � ���������� ���������

public class GPSActivity extends Activity implements OnCheckedChangeListener
{
	
	private boolean D = false;
	String TAG = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>GPSActivity";
	
	//boolean useImperial = false;
	
	GeneralLocationListener gpsLocationListener;
	//GeneralLocationListener towerLocationListener;
	public LocationManager gpsLocationManager;
	//public LocationManager towerLocationManager;
	
	//boolean towerEnabled;
	boolean gpsEnabled;
	boolean isStarted;
	boolean isUsingGps;
	
	public double currentLatitude;
	public double currentLongitude;
	
	int satellites;
	int minimumDistance;
	int minimumSeconds;
	//boolean preferCellTower;
	
	long latestTimeStamp;
	
	//Notification
	private NotificationManager gpsNotifyManager;
	private int NOTIFICATION_ID;
	boolean showInNotificationBar;
	boolean notificationVisible;

	
    // Message types sent from the BluetoothService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    
    private TextView mTitle;
    
    
    // Intent request codes
    //private static final int REQUEST_CONNECT_DEVICE = 1;
    //private static final int REQUEST_ENABLE_BT = 2;
    
    // Key names received from the BluetoothService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    
    // Name of the connected device
    private String mConnectedDeviceName = null;
    // Array adapter for the conversation thread
    //private ArrayAdapter<String> mConversationArrayAdapter;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the services
    private BluetoothService btService = null;
    
    private Boolean firstRun = true; // ��� ����, ����� �� ��������� ������ ��� ������� � ��������� �� - ������� ��������
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
		ToggleButton buttonOnOff = (ToggleButton) findViewById(R.id.buttonOnOff);
		buttonOnOff.setOnCheckedChangeListener(this);
		
		Intent i = getIntent();
		Bundle bundle = i.getExtras();
		
		if (bundle != null)
		{
			boolean startRightNow = bundle.getBoolean("immediate");
			if (startRightNow)
			{
				Log.w(TAG,"Auto starting logging");
				buttonOnOff.setChecked(true);
				onCheckedChanged(buttonOnOff, true);
			}
		}

		GetPreferences();
		mTitle = (TextView) findViewById(R.id.txtBTStatus);
		// Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        StartGpsManager();
    }
    
	/**
	 * Called when the toggle button is clicked
	 */
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
	{
		try
		{
			if (isChecked)
			{
				if (!gpsLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
		        {
		        	startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));
		        	ToggleButton buttonOnOff = (ToggleButton) findViewById(R.id.buttonOnOff);
		        	onCheckedChanged(buttonOnOff, false);
		        }
				else
				{
					if (isStarted)
					{
						return;
					}
					Log.w(TAG,"Starting logging procedures");
					isStarted = true;
					GetPreferences();
					Notify();
					ClearForm();
					StartGpsManager();
				}
			}
			else
			{
				Log.w(TAG,"Stopping logging");
				isStarted = false;
				RemoveNotification();
				StopGpsManager();
			}

		}
		catch (Exception ex)
		{
			Log.e("onCheckedChanged", ex.toString());
			SetStatus(getString(R.string.button_click_error) + ex.getMessage());
		}
	}

    @Override
    protected void onDestroy() {
    	super.onDestroy();
        // Stop the Bluetooth services
    	this.unregisterReceiver(mReceiver);
        if (btService != null) btService.stop();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }
    
    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    protected synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (btService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (btService.getState() == BluetoothService.STATE_NONE) {
              // Start the Bluetooth services
              btService.start();
            }
        }
        else
        {
        	initService();
        }
    }
    
    @Override
    protected void onStart() {
    	super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setup() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            //Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            //startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            ensureDiscoverable();
        // Otherwise, setup the  session
        } 
        else 
        {
            if (btService == null) initService();
        }
    }
	private void initService() {
		if(D) Log.d(TAG, "initService()");
        // Initialize the BluetoothService to perform bluetooth connections
        btService = new BluetoothService(this, mHandler);
        ensureDiscoverable();
        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }
	
	private void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        if (firstRun)
        {
	        if (mBluetoothAdapter.getScanMode() !=
	            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
	            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
	            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
	            startActivity(discoverableIntent);
	        }
	        firstRun = false;
        }
    }
    @Override
    protected void onRestart() {
    	super.onRestart();
        Log.w(TAG,"onrestart");
    }
    
    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }
    
	/**
	 * Stops location manager, then starts it.
	 */
	public void RestartGpsManagers()
	{
		Log.i(TAG,"Restarting GPS Managers");
		StopGpsManager();
		StartGpsManager();
	}
	
	private void CheckTowerAndGpsStatus()
	{
		if (D)Log.i(TAG,"CheckTowerAndGpsStatus");
		gpsEnabled = gpsLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}
 
	public void StartGpsManager()
	{
		ClearForm();
		Log.i(TAG,"StartGpsManager");
		gpsLocationListener = new GeneralLocationListener(this);

		gpsLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		CheckTowerAndGpsStatus();

		if (gpsEnabled)
		{
			// gps satellite based
			gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
					minimumSeconds * 1000, minimumDistance, gpsLocationListener);

			gpsLocationManager.addGpsStatusListener(gpsLocationListener);

			isUsingGps = true;
			Toast.makeText(getBaseContext(), getString(R.string.toast_gpsStart), Toast.LENGTH_SHORT).show();
		}

		else
		{
			isUsingGps = false;
			SetStatus(R.string.gpsprovider_unavailable);
			Log.i(TAG,"gpsprovider_unavailable");
			return;
		}
		SetStatus(R.string.started);
	}
	
	/**
	 * Stops the location managers
	 */
	public void StopGpsManager()
	{
		if (gpsLocationListener != null)
		{
			gpsLocationManager.removeUpdates(gpsLocationListener);
			gpsLocationManager.removeGpsStatusListener(gpsLocationListener);
		}
		SetStatus(R.string.stopped);
		Log.i(TAG,"Stopped");
	}
	/**
	 * Checks to see if providers have been enabled and switches providers based
	 * on user preferences.
	 */
	public void ResetManagersIfRequired()
	{
		if (D) Log.i(TAG,"ResetManagersIfRequired");
		CheckTowerAndGpsStatus();
		RestartGpsManagers();
	}
	/**
	 * Sets the message in the top status label.
	 * 
	 * @param message
	 */
	public void SetStatus(String message)
	{
		TextView tvStatus = (TextView)findViewById(R.id.textStatus);
		tvStatus.setText(message);
	}
	public void SetStatus(int stringId)
	{
		String s = getString(stringId);
		SetStatus(s);
	}
	
	/**
	 * Sets the number of satellites in the satellite row in the table.
	 * 
	 * @param number
	 */
	public void SetSatelliteInfo(int number)
	{
		satellites = number;
		TextView txtSatellites = (TextView) findViewById(R.id.txtSatellites);
		txtSatellites.setText(String.valueOf(number));
	}
	/**
	 * Clears the table, removes all values.
	 */
	private void ClearForm()
	{
		TextView tvLatitude = (TextView) findViewById(R.id.txtLatitude);
		TextView tvLongitude = (TextView) findViewById(R.id.txtLongitude);
		TextView tvDateTime = (TextView) findViewById(R.id.txtDateTimeAndProvider);
		TextView tvAltitude = (TextView) findViewById(R.id.txtAltitude);
		TextView txtSpeed = (TextView) findViewById(R.id.txtSpeed);
		TextView txtSatellites = (TextView) findViewById(R.id.txtSatellites);
		TextView txtDirection = (TextView) findViewById(R.id.txtDirection);
		TextView txtAccuracy = (TextView) findViewById(R.id.txtAccuracy);

		tvLatitude.setText("");
		tvLongitude.setText("");
		tvDateTime.setText("");
		tvAltitude.setText("");
		txtSpeed.setText("");
		txtSatellites.setText("");
		txtDirection.setText("");
		txtAccuracy.setText("");
	}
	
	/**
	 * Called when the menu is created.
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.optionsmenu, menu);

		if (!Utilities.Flag())
		{
			menu.getItem(1).setVisible(false);
		}
		return true;
	}
	/**
	 * Called when one of the menu items is selected.
	 */
	public boolean onOptionsItemSelected(MenuItem item)
	{
		int itemId = item.getItemId();
		Log.i(TAG,"Option item selected - " + String.valueOf(item.getTitle()) );

		switch (itemId)
		{
			case R.id.mnuSettings:
				Intent settingsActivity = new Intent(getBaseContext(), GpsSettingsActivity.class);
				startActivity(settingsActivity);
				break;
			case R.id.mnuExit:
				RemoveNotification();
				StopGpsManager();
				System.exit(0);
				break;
		}
		return false;
	}
	/**
	 * Given a location fix, processes it and displays it in the table on the
	 * form.
	 * 
	 * @param loc
	 */
	public void DisplayLocationInfo(Location loc)
	{
		try
		{
			long currentTimeStamp = System.currentTimeMillis();
			if ((currentTimeStamp - latestTimeStamp) < (minimumSeconds * 1000))
			{
				return;
			}

			latestTimeStamp = System.currentTimeMillis();

			Notify();

			TextView tvLatitude = (TextView) findViewById(R.id.txtLatitude);
			TextView tvLongitude = (TextView) findViewById(R.id.txtLongitude);
			TextView tvDateTime = (TextView) findViewById(R.id.txtDateTimeAndProvider);

			TextView tvAltitude = (TextView) findViewById(R.id.txtAltitude);

			TextView txtSpeed = (TextView) findViewById(R.id.txtSpeed);

			TextView txtSatellites = (TextView) findViewById(R.id.txtSatellites);
			TextView txtDirection = (TextView) findViewById(R.id.txtDirection);
			TextView txtAccuracy = (TextView) findViewById(R.id.txtAccuracy);
			String providerName = loc.getProvider();

			if (providerName.equalsIgnoreCase("gps"))
			{
				providerName = getString(R.string.providername_gps);
			}
			else
			{
				providerName = getString(R.string.providername_celltower);
			}

			tvDateTime.setText(new Date().toLocaleString()
					+ getString(R.string.providername_using, providerName));
			tvLatitude.setText(String.valueOf(loc.getLatitude()));
			tvLongitude.setText(String.valueOf(loc.getLongitude()));

			if (loc.hasAltitude())
			{

				double altitude = loc.getAltitude();

				/*if (useImperial)
				{
					tvAltitude.setText(String.valueOf(Utilities.MetersToFeet(altitude))
							+ getString(R.string.feet));
				}
				else
				{*/
					tvAltitude.setText(String.valueOf(altitude) + getString(R.string.meters));
				//}

			}
			else
			{
				tvAltitude.setText(R.string.not_applicable);
			}

			if (loc.hasSpeed())
			{

				float speed = loc.getSpeed();
				/*if (useImperial)
				{
					txtSpeed.setText(String.valueOf(Utilities.MetersToFeet(speed))
							+ getString(R.string.feet_per_second));
				}
				else
				{*/
					txtSpeed.setText(String.valueOf(speed) + getString(R.string.meters_per_second));
				//}

			}
			else
			{
				txtSpeed.setText(R.string.not_applicable);
			}

			if (loc.hasBearing())
			{

				float bearingDegrees = loc.getBearing();
				String direction = getString(R.string.unknown_direction);

				direction = Utilities.GetBearingDescription(bearingDegrees, getBaseContext());

				txtDirection.setText(direction + "(" + String.valueOf(Math.round(bearingDegrees))
						+ getString(R.string.degree_symbol) + ")");
			}
			else
			{
				txtDirection.setText(R.string.not_applicable);
			}

			if (!isUsingGps)
			{
				txtSatellites.setText(R.string.not_applicable);
				satellites = 0;
			}

			if (loc.hasAccuracy())
			{

				float accuracy = loc.getAccuracy();
				txtAccuracy.setText(getString(R.string.accuracy_within, String.valueOf(accuracy),
						getString(R.string.meters)));

			}
			else
			{
				txtAccuracy.setText(R.string.not_applicable);
			}

			GetPreferences();
			//http://ru.wikipedia.org/wiki/NMEA
			/*
			 * $GPRMC,hhmmss.ss,A,GGMM.MM,P,gggmm.mm,J,v.v,b.b,ddmmyy,x.x,n,m*hh<CR><LF>
				(�������� � ��������� ������ ������ ���).
				�������� �����:
				�GP� � ���� �������� GPS (� ��������� �������� �GL� ��������������� ��� �������)
				�RMC� � �Recommended Minimum sentence C�
				�hhmmss.ss� � ����� �������� �������������� �� �������� UTC: �hh� � ����, �mm� � ������, �ss.ss� � �������. ����� ������� ����� ������ �����������. ���������� ���� �� ����������.
				�A� � ������: �A� � ������ ����������, �V� � ������������.
				�GGMM.MM� � ������. 2 ����� ��������(�GG�), 2 ����� ����� �����, ����� � ������� ����� ����� ���������� �����. ���������� ���� �� ����������.
				�P� � �N� ��� �������� ��� �S� ��� ����� ������.
				�gggmm.mm� � �������. 3 ����� ��������(�ggg�), 2 ����� ����� �����, ����� � ������� ����� ����� ���������� �����. ���������� ���� �� ����������.
				�J� � �E� ��� ��������� ��� �W� ��� �������� �������.
				�v.v� � �������������� ������������ �������� ������������ ����� � �����. ����� � ��������� ������. ����� � ������� ����� ���������� �����.
				�b.b� � ������� ���� (����������� ��������) � ��������. ����� � ��������� ������. ����� � ������� ����� ���������� �����. �������� ������ 0 ������������� �������� �� �����, 90 � ������, 180 � ��, 270 � �����.
				�ddmmyy� � ����: ���� ������, �����, ��������� 2 ����� ���� (������� ���� �����������).
				�x.x� � ��������� ��������� � �������� (����� �����������), ������������ �� ��������� ������. ����� � ��������� ������. ����� � ������� ����� ���������� �����.
				�n� � ����������� ���������� ���������: ��� ��������� ���������� ����� ��������� ��������� ���������� �E� � �������, �W� � ��������� � ��������� �����.
				�m� � ��������� ������: �A� � ����������, �D� � ����������������, �E� � �������������, �N� � ������������� ������ (����� �����������, ������ ���� ������� ������� ����������� � ������ ������� NMEA).
				�hh� � ����������� �����.
				<CR> � ���� ����� 0x0D.
				<LF> � ���� ����� 0x0A.
			 */
			Date fulldate = new Date();
			
			
			String time = Utilities.GetFullTime(fulldate);	
			String date = Utilities.GetFullDate(fulldate);
			
			double speed =0.0;
			if (loc.hasSpeed()) { speed = Utilities.MetersPerSecToKilometersPerHour(loc.getSpeed());}
			
			double bearingDegrees = 0.0;
			if (loc.hasBearing()){ bearingDegrees = loc.getBearing();}
			
			Coordinate Lat = Utilities.GetCoordinate(Location.convert(loc.getLatitude(), 1),0);
			Coordinate Lon = Utilities.GetCoordinate(Location.convert(loc.getLongitude(), 1),1);
			
 			String sendText ="GPRMC"+","+time+","+"A"
				+","+Lat.getHour()+Lat.getMinute()+","+Lat.getNSEW()
				+","+Lon.getHour()+Lon.getMinute()+","+Lon.getNSEW()
				+","+String.valueOf(speed)+","+bearingDegrees+","+date+",,"; 
			sendText = "$"+sendText+"*"+Utilities.getChecksum(sendText);//+cr+lf;
			//Log.w(TAG,"NMEA string " + sendText);
			sendMessage(sendText);
		}
		catch (Exception ex)
		{
			SetStatus(getString(R.string.error_displaying, ex.getMessage()));
			Log.w(TAG,"error"+ex);
		}
	}
	
	public void GetPreferences()
	{
		if (D) Log.w(TAG,"Getting preferences");
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		showInNotificationBar = prefs.getBoolean("show_notification", true);
	}
	/**
	 * Manages the notification in the status bar
	 */
	private void Notify()
	{
		//Log.w(TAG,"Notification");
		if (showInNotificationBar)
		{
			gpsNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			ShowNotification();
		}
		else
		{
			RemoveNotification();
		}
	}

	/**
	 * Hides the notification icon in the status bar if it's visible.
	 */
	private void RemoveNotification()
	{
		//Log.w(TAG,"Remove notification");
		try
		{
			if (notificationVisible)
			{
				gpsNotifyManager.cancelAll();
			}
		}
		catch (Exception ex)
		{
			Log.e("RemoveNotification", ex.toString());
		}
		finally
		{
			notificationVisible = false;
		}
	}

	/**
	 * Shows a notification icon in the status bar for GPS Logger
	 */
	private void ShowNotification()
	{
		// What happens when the notification item is clicked
		Intent contentIntent = new Intent(this, GPSActivity.class);

		PendingIntent pending = PendingIntent.getActivity(getBaseContext(), 0, contentIntent,
				android.content.Intent.FLAG_ACTIVITY_NEW_TASK);

		Notification nfc = new Notification(R.drawable.share1, null, System.currentTimeMillis());
		nfc.flags |= Notification.FLAG_ONGOING_EVENT;

		NumberFormat nf = new DecimalFormat("###.######");

		String contentText = getString(R.string.gpsreciver_still_running);
		if (currentLatitude != 0 && currentLongitude != 0)
		{
			contentText = nf.format(currentLatitude) + "," + nf.format(currentLongitude);
		}

		nfc.setLatestEventInfo(getBaseContext(), getString(R.string.gpsreciver_still_running),
				contentText, pending);

		gpsNotifyManager.notify(NOTIFICATION_ID, nfc);
		notificationVisible = true;
	}

	/**
	 * Handles the hardware back-button press
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		Log.w(TAG,"KeyDown - " + String.valueOf(keyCode));

		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			moveTaskToBack(true);
			Toast.makeText(getBaseContext(), getString(R.string.toast_gpsreciver_stillrunning),Toast.LENGTH_LONG).show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	/**
	 * Update the UI: There was a connection error
	 */
	public final Runnable updateResultsConnectionError = new Runnable()
	{
		public void run()
		{
			ThereWasAConnectionError();
		}
	};
	/**
	 * MessageBox: There was a connection error.
	 */
	private void ThereWasAConnectionError()
	{
		Utilities.MsgBox(getString(R.string.error), getString(R.string.error_connection), this);
	}
	
    /**
     * Sends a message.
     * @param message  A string of text to send.
     */
    private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (btService.getState() != BluetoothService.STATE_CONNECTED) {
            //Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothService to write
            byte[] send = message.getBytes();
            btService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
        }
    }
    
 // The Handler that gets information back from the BluetoothService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothService.STATE_CONNECTED:
                    mTitle.setText(R.string.title_connected_to);
                    mTitle.append(mConnectedDeviceName);
                    //mConversationArrayAdapter.clear();
                    break;
                case BluetoothService.STATE_CONNECTING:
                    mTitle.setText(R.string.title_connecting);
                    break;
                case BluetoothService.STATE_LISTEN:
                case BluetoothService.STATE_NONE:
                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;

            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
    

    // The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                
                // ���� �� ���� ��������� ���������� - ���������� "���� �������"
                if (btService.getState() != BluetoothService.STATE_CONNECTED) {
                	ensureDiscoverable();
                }
                
                /*setTitle(R.string.select_device);
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = getResources().getText(R.string.none_found).toString();
                    mNewDevicesArrayAdapter.add(noDevices);
                }*/
            }
        }
    };
}